//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.yonyou.iuap.formula.engine.formulaset;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.iuap.formula.common.IrisReferenceUtil;
import com.yonyou.iuap.formula.common.SpringContextHolder;
import com.yonyou.iuap.formula.engine.FormulaContext;
import com.yonyou.iuap.formula.service.IFormulaScriptService;
import com.yonyou.iuap.utils.HttpUtil;
import com.yonyou.ucf.mdd.api.interfaces.rpc.IComQueryApi;
import com.yonyou.ucf.mdd.ext.dubbo.DubboReferenceUtils;
import com.yonyoucloud.bill.service.ITranslateService;
import org.apache.commons.lang3.StringUtils;
import org.imeta.biz.base.BizContext;
import org.imeta.core.model.Entity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class CustomFunction {
    private static final Logger log = LoggerFactory.getLogger(CustomFunction.class);
    private static final Map<String, String> domainCache = new ConcurrentHashMap();
    private static final String getDomainURI = "/unified/entity/getDomainByEntityUri?";

    public CustomFunction() {
    }

    public static Object getValue(String fullName, String selectFiled, String conditionField, Object conditionValue) {
        try {
//            ITranslateService translateService = (ITranslateService)SpringContextHolder.getBean(ITranslateService.class);
            Entity entity = BizContext.getMetaRepository().entity(fullName);
            ITranslateService translateService = DubboReferenceUtils.getDubboService(ITranslateService.class, entity.domain(), null);
            List conditionList;
            if (!FormulaContext.getIsFuncOptimizedExecute()) {
                conditionList = translateService.getValue(fullName, selectFiled, conditionField, conditionValue);
                return CollectionUtils.isEmpty(conditionList) ? null : conditionList.get(0);
            } else {
                conditionList = (List)conditionValue;
                List<Map<String, Object>> rpcResult = translateService.getValue(fullName, selectFiled, conditionField, conditionList);
                List<Object> resultList = new ArrayList();
                String findFiled = selectFiled.replace(".", "_");
                Iterator var9 = conditionList.iterator();

                while(true) {
                    while(var9.hasNext()) {
                        Object conditionItemValue = var9.next();
                        if (conditionItemValue == null) {
                            resultList.add((Object)null);
                        } else {
                            Map<String, Object> resultMap = (Map)rpcResult.stream().filter((r) -> {
                                return conditionItemValue.toString().equals(r.get(conditionField).toString());
                            }).findFirst().orElse((Map<String, Object>) null);
                            if (resultMap != null && resultMap.containsKey(findFiled)) {
                                resultList.add(resultMap.get(findFiled));
                            } else {
                                resultList.add((Object)null);
                            }
                        }
                    }

                    return resultList;
                }
            }
        } catch (Exception var12) {
            log.error("自定义函数getValue异常：" + var12.getMessage(), var12);
            return null;
        }
    }

    public static Object getValueMore(String fullName, String selectFiled, Object... conditions) {
        try {
            String domain = getDomainByFullName(fullName);
            log.error("execute getValueMore函数，通过uri:{} 获取到domain:{}", fullName, domain);
            IComQueryApi comQueryApi;
            if (StringUtils.isNotBlank(domain)) {
                comQueryApi = (IComQueryApi)IrisReferenceUtil.getRPCReference(domain, IComQueryApi.class);
            } else {
                log.error("函数getValueMore异常：根据fullName={}获取domain为空, 尝试使用本地调用", fullName);
                comQueryApi = (IComQueryApi)SpringContextHolder.getBean(IComQueryApi.class);
            }

            if (comQueryApi != null) {
                List<Map<String, Object>> list = comQueryApi.query(fullName, processCondition(selectFiled, conditions));
                return CollectionUtils.isEmpty(list) ? null : ((List)list.stream().map((i) -> {
                    return i.get(selectFiled.replace(".", "_"));
                }).collect(Collectors.toList())).get(0);
            } else {
                log.error("函数getValueMore异常：没有找到IComQueryApi的本地实现或远程实现, fullName=" + fullName);
                return null;
            }
        } catch (Exception var6) {
            log.error("函数getValueMore异常：" + var6.getMessage(), var6);
            return null;
        }
    }

    private static String processCondition(String selectFiled, Object... params) {
        if ((params.length & 1) == 1) {
            throw new RuntimeException("条件key-value个数不匹配");
        } else if (params.length > 16) {
            throw new RuntimeException("条件key-value数超长，最大支持8对");
        } else {
            JSONObject out = new JSONObject();
            JSONArray fields = new JSONArray();
            JSONArray conditions = new JSONArray();
            out.put("fields", fields);
            out.put("conditions", conditions);
            JSONObject condition = new JSONObject();
            condition.put("op", "and");
            conditions.add(condition);
            JSONObject selectField = new JSONObject();
            selectField.put("name", selectFiled);
            fields.add(selectField);
            JSONArray items = new JSONArray();
            condition.put("items", items);

            for(int i = 0; i < params.length; ++i) {
                if ((i & 1) == 0) {
                    JSONObject conditionField = new JSONObject();
                    conditionField.put("name", Objects.toString(params[i]));
                    fields.add(conditionField);
                    JSONObject item = new JSONObject();
                    item.put("name", params[i]);
                    item.put("op", "in");
                    JSONArray fieldValue = new JSONArray();
                    fieldValue.add(params[i + 1]);
                    item.put("v1", fieldValue);
                    items.add(item);
                }
            }

            return out.toJSONString();
        }
    }

    public static String getDomainByFullName(String fullName) {
        String tenantId = InvocationInfoProxy.getTenantid();
        String metadataUrl = ((Environment)SpringContextHolder.getBean(Environment.class)).getProperty("domain.iuap-metadata-base");
        if (StringUtils.isBlank(metadataUrl)) {
            metadataUrl = ((Environment)SpringContextHolder.getBean(Environment.class)).getProperty("metadata.api.url");
        }

        log.info("formula:metadataUrl->{}", metadataUrl);
        if (StringUtils.isAnyBlank(new CharSequence[]{tenantId, metadataUrl})) {
            return null;
        } else {
            String url = metadataUrl + "/unified/entity/getDomainByEntityUri?" + "uri=" + fullName + "&tenantId=" + tenantId;
            if (domainCache.containsKey(url)) {
                return (String)domainCache.get(url);
            } else {
                try {
                    String get = HttpUtil.getInstance().doGetForString(url);
                    JSONObject jsonObject = JSON.parseObject(get);
                    if (!jsonObject.get("resultCode").equals("200")) {
                        log.error("根据fullName{}获取domain异常,接口返回值{},请检查元数据配置", fullName, jsonObject.get("resultCode"));
                    }

                    String domain = (String)jsonObject.get("data");
                    if (StringUtils.isEmpty(domain)) {
                        log.error("根据fullName{}获取domain接口返回值为空,请检查uri", fullName);
                        return domain;
                    } else {
                        domainCache.put(url, domain);
                        return domain;
                    }
                } catch (Exception var7) {
                    log.error("根据fullName{}获取domain异常", fullName, var7);
                    return null;
                }
            }
        }
    }

    public static Object getID(String uri, String name, String id) {
        return id;
    }

    public static Object def(String funcName, Object... args) {
        log.info("def函数执行[{}][{}]", funcName, args);
        return funcName;
    }

    public static Object publicScriptFormula(String extScriptId, List<Object> params, String debugCode) {
        if (StringUtils.isBlank(extScriptId)) {
            throw new RuntimeException("公式脚本计算时脚本Id不存在");
        } else if (CollectionUtils.isEmpty(params)) {
            throw new IllegalArgumentException("公式脚本计算时脚本的参数值不存在");
        } else {
            if (log.isInfoEnabled()) {
                log.info("脚本函数正在进行计算--->参数为apiRequest{}，extScriptId{},debugCode{}", new Object[]{JSON.toJSONString(params), extScriptId, debugCode});
            }

            return batchScriptFormula(extScriptId, params, debugCode);
        }
    }

    private static Object batchScriptFormula(String extScriptId, List<Object> params, String debugCode) {
        IFormulaScriptService scriptService = (IFormulaScriptService)IrisReferenceUtil.getRPCReference((String)null, IFormulaScriptService.class);
        return scriptService.scriptFormulaByRest(extScriptId, params, debugCode);
    }

    private static Object ordinaryScriptFormula(String extScriptId, List<Object> params, String debugCode) {
        IFormulaScriptService scriptService = (IFormulaScriptService)IrisReferenceUtil.getRPCReference((String)null, IFormulaScriptService.class);
        return scriptService.scriptFormulaByRest(extScriptId, params, debugCode);
    }
}
